<template>
  <div>
    <div>
      <div class="searchForm">
        <el-form :inline="true" :model="params" class="demo-form-inline">
          <el-form-item label="标题">
            <el-input
              v-model="params.name"
              placeholder="按skuID 商品名称 属性查找"
              class="block"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="getList(1)"
              class="block"
              >查询</el-button
            >
            <el-button icon="el-icon-plus" class="block" @click="add"
              >增加</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              class="block"
              @click="removeMore"
              >批量删除</el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <div class="message">
        <el-table
          :data="rows"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column prop="skuId" label="sku编码"> </el-table-column>
          <el-table-column prop="salePrice" label="售价"> </el-table-column>
          <el-table-column prop="originalPrice" label="原价"> </el-table-column>
          <el-table-column prop="productName" label="商品名称">
          </el-table-column>
          <el-table-column prop="imgs" label="图片">
            <template slot-scope="scope">
              <img
                style="width: 40px; height: 40px"
                v-if="scope.row.imgs"
                :src="scope.row.imgs"
              />
            </template>
          </el-table-column>
          <el-table-column prop="props" label="属性"> </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="edit(scope.row)"
                >编辑</el-button
              >
              <el-popconfirm
                title="确定删除此数据吗？"
                @confirm="remove(scope.row)"
              >
                <el-button
                  icon="el-icon-delete"
                  type="danger"
                  style="margin-left: 10px"
                  size="mini"
                  slot="reference"
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <el-pagination
          @size-change="sizeChange"
          @current-change="getList"
          :current-page="params.pageNum"
          :page-sizes="[5, 10, 100, 200, 300, 400]"
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <el-dialog
      :title="form._id ? '修改' : '新增'"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
      width="400px"
    >
      <el-form :model="form" ref="form" :rules="rules" label-width="100px">
        <el-form-item label="轮播图片" prop="imgs" style="margin-bottom: 20px">
          <div
            @click="openFile"
            style="
              width: 100px;
              height: 100px;
              font-size: 32px;
              border: 1px dashed #ccc;
              text-align: center;
              line-height: 100px;
              opacity: 0.5;
              overflow: hiddrn;
            "
          >
            <img
              style="max-width: 100%; max-height: 100%"
              v-if="form.imgs"
              :src="form.imgs"
            />
            <span v-else>+</span>
          </div>
          <input
            ref="file"
            style="display: none"
            type="file"
            multiple
            accept="image/*"
            @change="changeFile"
          />
        </el-form-item>
        <el-form-item label="SKU编码" prop="skuId" style="margin-bottom: 20px">
          <el-input type="text" v-model="form.skuId"></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="salePrice" style="margin-bottom: 20px">
          <el-input type="text" v-model="form.salePrice"></el-input>
        </el-form-item>
        <el-form-item
          label="原价"
          prop="originalPrice"
          style="margin-bottom: 20px"
        >
          <el-input type="text" v-model="form.originalPrice"></el-input>
        </el-form-item>
        <el-form-item label="属性" prop="props" style="margin-bottom: 20px">
          <el-input type="text" v-model="form.props"></el-input>
        </el-form-item>
        <el-form-item
          label="商品名称"
          prop="productName"
          style="margin-bottom: 20px"
        >
          <el-select v-model="form.productId" placeholder="请选择商品">
            <el-option
              v-for="(item, index) in rowes"
              :key="index"
              :label="item.name"
              :value="item._id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="canle">取消</el-button>
        <el-button type="primary" @click="submit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import api from "@/api";
export default {
  name: "sku",
  components: {
    //HelloWorld
  },
  data() {
    return {
      params: {
        name: "",
        pageNum: 1,
        pageSize: 5,
      },
      rows: [],
      total: 0,
      dialogFormVisible: false,
      rowes: [], //存放所有启用的数据
      form: {
        _id: 0,
        skuId: "",
        salePrice: "",
        originalPrice: "",
        props: "",
        productName: "",
        imgs: "",
        productId: "",
      },
      rules: {
        imgs: [{ required: true, message: "图片不能为空", trigger: "blur" }],
        skuId: [
          { required: true, message: "SKU编码唯一切不能为空", trigger: "blur" },
        ],
        productName: [
          { required: true, message: "品牌不能为空", trigger: "blur" },
        ],
      },
      selecteds: [],
      ID: "", //用户缓存编辑form的skuid
    };
  },
  methods: {
    //触发文件打开 点击加号
    openFile() {
      let fileElement = this.$refs.file;
      fileElement.click();
    },
    //监听上传文件事件
    changeFile(e) {
      let files = e.target.files;
      let formData = new FormData();
      formData.append("file", files[0]);
      this.$http({
        url: "upload",
        method: "POST",
        data: formData,
      }).then((res) => {
        if (res.filename)
          this.form.imgs = api.baseURL + "/uploads/" + res.filename;
        console.log(this.form);
      });
    },
    //关闭弹窗前的回调
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          this.getList(1);
          done();
        })
        .catch(() => {});
    },
    //取消弹窗刷新列表
    canle() {
      this.dialogFormVisible = false;
      this.getList(1);
    },
    //获取列表
    getList(pageNum) {
      if (pageNum) this.params.pageNum = pageNum;
      this.$http({
        url: "/admin/index/sku",
        params: this.params,
      }).then((res) => {
        this.total = res.total;
        this.rows = res.rows;
      });
    },
    //获取商品列表i
    getBrandList() {
      this.$http({
        url: "/admin/index/product",
      }).then((res) => {
        this.rowes = res.rows;
        console.log(this.rowes);
      });
    },
    removeMore() {
      //获取选中的数据
      let checkedRowsPromse = [];
      let success = [],
        fail = [];
      for (let i = 0; i < this.selecteds.length; i++) {
        checkedRowsPromse.push(
          new Promise((resovle) => {
            let row = this.selecteds[i];
            this.$http({
              url: "/admin/index/sku",
              method: "DELETE",
              params: { indexId: row._id },
            }).then((res) => {
              if (!res.errorMsg) {
                success.push(row._id);
              } else {
                fail.push(row._id);
              }
              resovle();
            });
          })
        );
      }
      ///删除
      Promise.all(checkedRowsPromse).then(() => {
        this.$message({
          message: `批量删除完成，成功删除${success.length}条数据，删除失败${fail.length}条数据`,
          duration: 3000,
        });
        this.getList(1);
      });
    },
    //编辑时取消按钮改变页面显示值 解决办法 点击取消时 重新渲染一次页面
    cancel() {
      this.getList(1);
      this.dialogFormVisible = false;
    },
    handleSelectionChange(rows) {
      //存储选中数据
      this.selecteds = rows;
    },
    //修改pagesize
    sizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.getList(1);
    },
    add() {
      //初始化
      this.form = {
        _id: 0,
        skuId: "",
        salePrice: "",
        originalPrice: "",
        props: "",
        productName: "",
        imgs: "",
        productId: "",
      };
      this.dialogFormVisible = true;
    },
    edit(row) {
      this.ID = row.skuId;
      this.form = row;
      this.form.productId = row.productName;
      this.dialogFormVisible = true;
    },
    //删除
    remove(row) {
      this.$http({
        url: "/admin/index/sku",
        method: "DELETE",
        params: { indexId: row._id },
      }).then((res) => {
        if (!res.errorMsg) {
          this.getList(1);
        }
      });
    },
    //通过商品表的-id找到productName
    findproductName() {
      let id = this.form.productId;
      for (let i = 0; i < this.rowes.length; i++) {
        if (id == this.rowes[i]._id) {
          this.form.productName = this.rowes[i].name;
        }
      }
    },
    //校验skuid是不是唯一的
    CheckId() {
      return new Promise((resovle) => {
        this.$http({
          url: "/admin/index/checkId",
          method: "PUT",
          data: this.form,
        }).then((res) => {
          console.log(res);
          this.state = res;
          resovle("状态数据写入完成！");
        });
      });
    },
    submit() {
      if (this.form.skuId != this.ID) {
        console.log("用户修改了skuID");
        this.CheckId().then((ret) => {
          console.log(ret, "数据更新成功");
          console.log("我先获取this.state", this.state);
          if (this.state) {
            this.findproductName();
            this.$refs.form.validate((valid) => {
              if (valid) {
                this.form.indexId = this.form._id;
                this.$http({
                  url: "/admin/index/sku",
                  method: this.form.indexId ? "PUT" : "POST", //通过indeid判断是新增还是编辑
                  data: this.form,
                }).then((res) => {
                  if (!res.errorMsg) {
                    this.dialogFormVisible = false;
                    this.getList(this.form.indexId ? undefined : 1);
                  }
                });
              }
            });
          } else {
            this.$message({
              message: `此skuId已被注册，请换其他skuId`,
              duration: 3000,
              type: "warning",
            });
          }
        });
      }else{
         this.findproductName();
            this.$refs.form.validate((valid) => {
              if (valid) {
                this.form.indexId = this.form._id;
                this.$http({
                  url: "/admin/index/sku",
                  method: this.form.indexId ? "PUT" : "POST", //通过indeid判断是新增还是编辑
                  data: this.form,
                }).then((res) => {
                  if (!res.errorMsg) {
                    this.dialogFormVisible = false;
                    this.getList(this.form.indexId ? undefined : 1);
                  }
                });
              }
            });
      }
    },
  },
  created() {
    this.getList();
    this.getBrandList();
  },
  mounted() {},
};
</script>

<style >
</style>